
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

FILE* fp;
void handler_signal(int signal)
{
    char buf[64] = { 0 };
    int len = 0;
    len = snprintf(buf, sizeof(buf) - 1, "recv signal=%d \n", signal);

    printf("%s", buf);
    // fprintf(fp,"%s",buf); // --> 运行出现 Segmentation fault (core dumped)
    fwrite(buf, 1, len, fp);  // --> 运行出现 Segmentation fault (core dumped)
}

int main()
{
    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_handler = handler_signal;
    act.sa_flags = 0;
    sigaction(SIGTERM, &act, 0);
    sigaction(SIGINT, &act, 0);

    fp = fopen("w", "/home/liuj/signal.log");
    while (1) {
        sleep(60);
    }

    return 0;
}

/* 运行
./22_linux_系统关机信号处理.out
^Crecv signal=2
Segmentation fault (core dumped)


kill -15 3075
recv signal=15
Segmentation fault (core dumped)
*/

/* 结论: 在信号回调函数中, 写文件, 出现段错误
 */